package com.ilancuo.tcp;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Created by Administrator on 2017/1/17.
 */
public class InetAddressDemo {
    public static void main(String[] args) {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            if (networkInterfaces == null) {
                System.out.print("-- No interface found--");
            } else {
                while (networkInterfaces.hasMoreElements()) {
                    NetworkInterface nextInterface = networkInterfaces.nextElement();
                    System.out.print("Interface " + nextInterface.getName() + "; ");
                    Enumeration<InetAddress> inetAddresses = nextInterface.getInetAddresses();
                    if (!inetAddresses.hasMoreElements()) {
                        System.out.println("\t No address for this interface.");
                    }
                    while (inetAddresses.hasMoreElements()) {
                        InetAddress address = inetAddresses.nextElement();
                        System.out.println("\taddress" + ((address instanceof Inet4Address ? "(V4)" : address instanceof Inet6Address ? "(V6)" : "(?)")));
                        System.out.println(":" + address.getHostAddress());
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
}
